<template>
  <div class="app-container">
    <el-row :gutter="15">
      <el-col :span="8">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>存储桶</span>
              <div>
                <el-input v-model="newBucket" placeholder="新建桶名" size="small" style="width: 160px; margin-right: 8px;" />
                <el-button type="primary" size="small" @click="onCreateBucket" :disabled="!newBucket">新建</el-button>
              </div>
            </div>
          </template>
          <el-table :data="buckets" height="520" @row-click="onSelectBucket">
            <el-table-column prop="name" label="名称" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-popconfirm title="确认删除该桶？(需为空)" @confirm="() => onDeleteBucket(scope.row.name)">
                  <template #reference>
                    <el-button type="danger" link>删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="16">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>对象 - {{ currentBucket || '未选择' }}</span>
              <div>
                <el-input v-model="prefix" placeholder="前缀筛选" size="small" style="width: 160px; margin-right: 8px;" />
                <el-switch v-model="recursive" active-text="递归" inactive-text="非递归" size="small" style="margin-right: 8px;" />
                <input ref="fileInput" type="file" style="display:none" @change="onUploadFile" />
                <el-button size="small" type="primary" @click="triggerUpload" :disabled="!currentBucket" style="margin-right:8px">上传</el-button>
                <el-button size="small" @click="loadObjects" :disabled="!currentBucket">刷新</el-button>
              </div>
            </div>
          </template>
          <el-table :data="objects" height="520">
            <el-table-column prop="objectName" label="对象名">
              <template #default="scope">
                <el-link type="primary" :underline="false" @click="copyName(scope.row)">{{ scope.row.objectName }}</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="size" label="大小" width="120" />
            <el-table-column prop="lastModified" label="修改时间" width="200">
              <template #default="scope">
                {{ formatDateTime(scope.row.lastModified) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
              <template #default="scope">
                <el-button link type="primary" @click="genPresign(scope.row)">预签名</el-button>
                <el-popconfirm title="确认删除该对象？" @confirm="() => onDeleteObject(scope.row)">
                  <template #reference>
                    <el-button link type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="预签名URL" v-model="presignDialog" width="600px">
      <el-form label-width="80px">
        <el-form-item label="有效期(s)">
          <el-input-number v-model="expires" :min="60" :max="7*24*3600" />
        </el-form-item>
      </el-form>
      <div class="presign-url-container">
        <div class="presign-url-label">生成的预签名URL:</div>
        <div class="presign-url">{{ presignUrl || '点击"生成"按钮获取预签名URL' }}</div>
        <el-button v-if="presignUrl" type="primary" size="small" @click="copyPresignUrl" style="margin-top: 10px;">复制URL</el-button>
      </div>
      <template #footer>
        <el-button type="primary" @click="doPresign" :loading="presignLoading">生成</el-button>
        <el-button @click="presignDialog=false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { listBuckets, createBucket, deleteBucket, listObjects, deleteObject, uploadToBucket, presign } from '@/api/race/cloud'

const buckets = ref([])
const objects = ref([])
const newBucket = ref('')
const currentBucket = ref('')
const prefix = ref('')
const recursive = ref(true)

const fileInput = ref(null)

const presignDialog = ref(false)
const presignUrl = ref('')
const expires = ref(3600)
const presignLoading = ref(false)
let currentObject = null

function loadBuckets() {
  listBuckets().then(res => {
    const arr = res.data || []
    buckets.value = arr.map(it => {
      if (typeof it === 'string') {
        return { name: it }
      }
      return { name: it.name || '', creationDate: it.creationDate }
    })
  })
}

function onCreateBucket() {
  if (!newBucket.value) return
  createBucket(newBucket.value).then(() => {
    newBucket.value = ''
    loadBuckets()
  })
}

function onDeleteBucket(bucket) {
  deleteBucket(bucket).then(() => {
    if (currentBucket.value === bucket) {
      currentBucket.value = ''
      objects.value = []
    }
    loadBuckets()
  })
}

function onSelectBucket(row) {
  currentBucket.value = row.name
  loadObjects()
}

function loadObjects() {
  if (!currentBucket.value) return
  listObjects({ bucket: currentBucket.value, prefix: prefix.value, recursive: recursive.value }).then(res => {
    const items = res.data || []
    objects.value = items.map(it => ({
      objectName: it.objectName || (it.name || ''),
      size: it.size,
      lastModified: it.lastModified
    }))
  })
}

function triggerUpload() {
  fileInput.value && fileInput.value.click()
}

function onUploadFile(e) {
  const file = e.target.files && e.target.files[0]
  if (!file || !currentBucket.value) return
  uploadToBucket(currentBucket.value, file).then(() => {
    loadObjects()
    e.target.value = ''
  })
}

function onDeleteObject(row) {
  deleteObject(currentBucket.value, row.objectName).then(() => {
    loadObjects()
  })
}

function genPresign(row) {
  currentObject = row
  presignDialog.value = true
  presignUrl.value = ''
}

function doPresign() {
  if (!currentObject) return
  presignLoading.value = true
  presignUrl.value = '' // 清空之前的URL
  
  console.log('生成预签名URL:', {
    bucket: currentBucket.value,
    object: currentObject.objectName,
    expires: expires.value
  })
  
  presign(currentBucket.value, currentObject.objectName, expires.value).then(res => {
    console.log('预签名URL完整响应:', res)
    console.log('响应类型:', typeof res)
    console.log('响应数据:', res.data)
    console.log('响应状态:', res.code)
    
    // 尝试不同的数据路径
    let url = null
    if (res && res.data) {
      url = res.data
    } else if (res && res.msg) {
      url = res.msg  // 预签名URL在msg字段中
    } else if (res && res.result) {
      url = res.result
    } else if (typeof res === 'string') {
      url = res
    }
    
    if (url) {
      presignUrl.value = url
      console.log('成功设置预签名URL:', presignUrl.value)
    } else {
      console.error('无法从响应中提取URL:', res)
      presignUrl.value = '获取预签名URL失败，请检查控制台错误信息'
    }
  }).catch(error => {
    console.error('获取预签名URL失败:', error)
    presignUrl.value = '请求失败: ' + error.message
  }).finally(() => {
    presignLoading.value = false
  })
}

function copyName(row) {
  if (!row || !row.objectName) return
  navigator.clipboard.writeText(row.objectName)
}

function copyPresignUrl() {
  if (!presignUrl.value) return
  navigator.clipboard.writeText(presignUrl.value).then(() => {
    console.log('预签名URL已复制到剪贴板')
  }).catch(err => {
    console.error('复制失败:', err)
  })
}

function pad2(n) {
  return n < 10 ? '0' + n : '' + n
}

function formatDateTime(val) {
  if (!val) return ''
  const d = new Date(val)
  if (isNaN(d.getTime())) return ''
  const y = d.getFullYear()
  const m = pad2(d.getMonth() + 1)
  const day = pad2(d.getDate())
  return `${y}-${m}-${day} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
}

loadBuckets()
</script>

<style scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.presign-url-container {
  margin-top: 20px;
}

.presign-url-label {
  font-weight: bold;
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
}

.presign-url {
  word-break: break-all;
  background: var(--el-fill-color-light);
  padding: 12px;
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
  font-family: monospace;
  font-size: 12px;
  line-height: 1.4;
  max-height: 120px;
  overflow-y: auto;
}
</style>


